//设置根路径
axios.defaults.baseURL = 'http://ajax-base-api-t.itheima.net'

//获取元素
const tb = document.querySelector('#tb')

const form = document.querySelector('#bookForm')

const booknameIpt = document.querySelector('input[name=bookname')
const authorIpt = document.querySelector('input[name=author')
const publisherIpt = document.querySelector('input[name=publisher')

//封装请求函数
const getBooklist = () => {
  axios({
    url: '/api/getbooks',
    method: 'get',
  }).then(({ data: res }) => {
    // console.log(res)
    const { data, msg, status } = res

    if (status !== 200) return alert(msg)
    //准备一个空字符串接收
    let htmlStr = ''

    //遍历data
    data.forEach(item => {
      htmlStr += `<tr>
      <td>${item.id}</td>
      <td>${item.bookname}</td>
      <td>${item.author}</td>
      <td>${item.publisher}</td>
      <td><a href="javascript:;" class="del" data-id='${item.id}'>删除</a></td>
    </tr>`
    })

    //渲染dom
    tb.innerHTML = htmlStr
  })
}

//封装添加事件
form.addEventListener('submit', function (e) {
  //阻止默认提交事件
  e.preventDefault()

  const ipt = serialize(this)

  // for (let key in ipt) {
  //   ipt[key] === ''
  // }

  // if (!booknameIpt.value || !authorIpt.value || !publisherIpt.value) return alert('请输入图书信息')
  if (Object.values(ipt).length < Object.keys(ipt).length) return alert('请输入图书信息')
  //使用form-serialize.js去获取表单的值
  const data = serialize(this)

  //提交表单数据
  axios({
    url: '/api/addbook',
    method: 'post',
    data,
  }).then(({ data: res }) => {
    console.log(res)
    alert(res.msg)
    getBooklist()
    if (res.status !== 201) return
    //reset方法可以直接重置表单中所有的内容
    form.reset()
  })
})

//添加删除事件
tb.addEventListener('click', function (e) {
  if (e.target.tagName === 'A') {
    const id = e.target.dataset.id

    axios({
      url: '/api/delbook?id=' + id,
      method: 'get',
    }).then(({ data: res }) => {
      const { msg } = res
      alert(msg)
      getBooklist()
    })
  }
})

//调用请求函数
getBooklist()
